package com.qiandao.xuexitong.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiandao.xuexitong.dto.ClassroomListDTO;
import com.qiandao.xuexitong.dto.CreateAttendanceTaskDTO;
import com.qiandao.xuexitong.entity.AttendanceTask;
import com.qiandao.xuexitong.entity.Classroom;
import com.qiandao.xuexitong.entity.ClassroomStudent;
import com.qiandao.xuexitong.entity.User;
import com.qiandao.xuexitong.enums.AttendanceTypeEnum;
import com.qiandao.xuexitong.exception.BusinessException;
import com.qiandao.xuexitong.mapper.AttendanceTaskMapper;
import com.qiandao.xuexitong.mapper.ClassroomMapper;
import com.qiandao.xuexitong.mapper.ClassroomStudentMapper;
import com.qiandao.xuexitong.mapper.UserMapper;
import com.qiandao.xuexitong.service.ClassroomService;
import com.qiandao.xuexitong.service.IClassroomStudentService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 班级信息表 服务实现类
 * </p>
 *
 * @author YouJiao
 * @since 2025-04-11
 */
@Service
@RequiredArgsConstructor
public class ClassroomServiceImpl extends ServiceImpl<ClassroomMapper, Classroom> implements ClassroomService {
    
    private final ClassroomMapper classroomMapper;
    private final ClassroomStudentMapper classroomStudentMapper;
    private final UserMapper userMapper;
    private final AttendanceTaskMapper attendanceTaskMapper;
    private final IClassroomStudentService classroomStudentService;
    
    @Override
    @Transactional
    public void createClassroom(Long teacherId, String name, String code) {
        // 检查班级编号是否已存在
        if (classroomMapper.exists(new LambdaQueryWrapper<Classroom>()
                .eq(Classroom::getCode, code))) {
            throw new BusinessException("班级编号已存在");
        }
        
        // 检查教师是否存在且是教师角色
        User teacher = userMapper.selectOne(
                new LambdaQueryWrapper<User>()
                        .eq(User::getId, teacherId)
                        .eq(User::getRole, 1)
        );
        if (teacher == null) {
            throw new BusinessException("教师不存在或不是教师角色");
        }
        
        // 创建班级
        Classroom classroom = new Classroom();
        classroom.setName(name);
        classroom.setCode(code);
        classroom.setTeacherId(teacherId);
        classroom.setCreateTime(LocalDateTime.now());
        save(classroom);
    }
    
    @Override
    public IPage<ClassroomListDTO> getClassroomList(Long teacherId, Page<ClassroomListDTO> page) {
        // 查询条件
        LambdaQueryWrapper<Classroom> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Classroom::getTeacherId, teacherId);
        
        // 先查询实体分页
        Page<Classroom> entityPage = new Page<>(page.getCurrent(), page.getSize());
        IPage<Classroom> classroomPage = page(entityPage, wrapper);
        
        // 转换为DTO分页
        return classroomPage.convert(classroom -> {
            ClassroomListDTO dto = new ClassroomListDTO();
            dto.setId(classroom.getId());
            dto.setName(classroom.getName());
            dto.setCode(classroom.getCode());
            
            // 查询班级学生数量
            Long count = classroomStudentMapper.selectCount(
                    new LambdaQueryWrapper<ClassroomStudent>()
                            .eq(ClassroomStudent::getClassroomId, classroom.getId())
            );
            dto.setStudentCount(count.intValue());
            
            return dto;
        });
    }
    
    @Override
    @Transactional
    public void addStudentsToClassroom(Long teacherId, Long classroomId, List<Long> studentIdList) {
        // 检查班级是否存在且属于该教师
        Classroom classroom = classroomMapper.selectOne(
                new LambdaQueryWrapper<Classroom>()
                        .eq(Classroom::getId, classroomId)
                        .eq(Classroom::getTeacherId, teacherId)
        );
        if (classroom == null) {
            throw new BusinessException("班级不存在或无权限");
        }
        
        // 检查学生是否存在且是学生角色
        for (Long studentId : studentIdList) {
            User student = userMapper.selectOne(
                    new LambdaQueryWrapper<User>()
                            .eq(User::getId, studentId)
                            .eq(User::getRole, 0)
            );
            if (student == null) {
                throw new BusinessException("学生不存在或不是学生角色");
            }
            
            // 检查是否已在班级中
            if (classroomStudentMapper.exists(
                    new LambdaQueryWrapper<ClassroomStudent>()
                            .eq(ClassroomStudent::getClassroomId, classroomId)
                            .eq(ClassroomStudent::getStudentId, studentId)
            )) {
                throw new BusinessException("学生已在班级中");
            }
            
            // 添加学生到班级
            ClassroomStudent classroomStudent = new ClassroomStudent();
            classroomStudent.setClassroomId(classroomId);
            classroomStudent.setStudentId(studentId);
            classroomStudentMapper.insert(classroomStudent);
        }
    }
    
    @Override
    @Transactional
    public void createAttendanceTask(Long teacherId, CreateAttendanceTaskDTO dto) {
        // 检查班级是否存在且属于该教师
        Classroom classroom = classroomMapper.selectOne(
                new LambdaQueryWrapper<Classroom>()
                        .eq(Classroom::getId, dto.getClassroomId())
                        .eq(Classroom::getTeacherId, teacherId)
        );
        if (classroom == null) {
            throw new BusinessException("班级不存在或无权限");
        }
        
        // 创建签到任务
        AttendanceTask task = new AttendanceTask();
        task.setClassroomId(dto.getClassroomId());
        task.setTeacherId(teacherId);
        task.setType(AttendanceTypeEnum.getByCode(dto.getType()));
        task.setTitle(dto.getTitle());
        task.setDescription(dto.getDescription());
        task.setStartTime(dto.getStartTime());
        task.setEndTime(dto.getEndTime());
        task.setStatus(0); // 初始状态为未结束
        task.setCreateTime(LocalDateTime.now());
        task.setUpdateTime(LocalDateTime.now());
        
        // 保存签到任务
        attendanceTaskMapper.insert(task);
    }

    @Override
    public List<Classroom> getStudentClassrooms(Long studentId) {
        // 1. 查询学生-班级关联记录
        List<ClassroomStudent> classroomStudents = classroomStudentService.lambdaQuery()
                .eq(ClassroomStudent::getStudentId, studentId)
                .list();
        
        if (classroomStudents.isEmpty()) {
            return Collections.emptyList();
        }
        
        // 2. 获取班级ID列表
        List<Long> classroomIds = classroomStudents.stream()
                .map(ClassroomStudent::getClassroomId)
                .collect(Collectors.toList());
        
        // 3. 查询班级信息
        return listByIds(classroomIds);
    }
}
